package mfh.liveroam.server;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.jdo.PersistenceManager;

import mfh.liveroam.client.PicasaBean;
import mfh.liveroam.client.PicasaService;
import mfh.liveroam.persistence.PMF;
import mfh.liveroam.persistence.RouteBean;

import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class PicasaServiceImpl extends RemoteServiceServlet implements
		PicasaService {

	public String greetServer(String input) {
		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");
		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	public ArrayList getAlbums(String userId) {
		ArrayList re = new ArrayList();
		URL feedUrl;
		try {
			feedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/"
					+ userId + "?kind=album");
			PicasawebService myService = new PicasawebService(
					"exampleCo-exampleApp-1");
			UserFeed myUserFeed = myService.getFeed(feedUrl, UserFeed.class);

			for (AlbumEntry myAlbum : myUserFeed.getAlbumEntries()) {
				String albumid = myAlbum.getId();
				albumid = albumid.replaceAll("feed/base", "feed/api");
				albumid = albumid.replaceAll("entry/api", "feed/api");

				PicasaBean bean = new PicasaBean();
				System.out.println(albumid);
				// System.out.println(myAlbum.getFeed().getIcon());

				System.out.println(myAlbum.getTitle().getPlainText());
				bean.setAlbumId(albumid);
				bean.setCaptrion(myAlbum.getTitle().getPlainText());
				this.setInfoByRouteBean(albumid, bean);

				re.add(bean);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return re;
	}

	private void setInfoByRouteBean(String albumId, PicasaBean bean) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		RouteBean routeBean = null;
		try {

			routeBean = pm.getObjectById(RouteBean.class, albumId);

			if (routeBean.getGpxStream() != null) {
				bean.setHasGpx(true);
				bean.setHourOffSet("" + routeBean.getHourOffset());
			}

		} catch (javax.jdo.JDOObjectNotFoundException e) {
			System.out.println(e.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}

	}

}
